package net.csdra.DongPoShuZiTuShuGuan.service;

import net.csdra.DongPoShuZiTuShuGuan.domain.Video;
import net.csdra.DongPoShuZiTuShuGuan.domain.VideoRepository;
import net.csdra.DongPoShuZiTuShuGuan.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * Created by add on 2018/1/17.
 */
@Service
public class VideoManagerServiceImpl implements VideoManagerService {
    @Autowired
    VideoRepository videoRepository;

    @Override
    public Video getVideo(GetVideo getVideo) {
        Assert.notNull(getVideo, "参数不能为空");
        Assert.hasText(getVideo.getId(), "id不能为空");
        Video video = this.videoRepository.findOne(getVideo.getId());
        return video;
    }

    @Override
    public Video createVideo(CreateVideo createVideo) {
        Assert.notNull(createVideo, "参数不能为空");
        Assert.hasText(createVideo.getVideoUrl(), "@视频不能为空");
        Video system = Utils.createAutoSet(Video.class, "system");
        Utils.copy(createVideo, system);
        this.videoRepository.save(system);
        Video result = new Video();
        Utils.copy(system, result);
        return result;
    }

    @Override
    public void deleteVideo(String id) {
        Video one = this.videoRepository.findOne(id);
        Assert.notNull(one, "@删除对象不存在");
        one.setDeleted(true);
        this.videoRepository.save(one);
    }

    @Override
    public Video updateVideo(UpdateVideo updateVideo) {
        Assert.notNull(updateVideo, "参数不能为空");
        Assert.hasText(updateVideo.getId(), "id不能为空");
        Video video = this.videoRepository.findOne(updateVideo.getId());
        Assert.notNull(video, "修改对象不存在");
        Utils.copy(updateVideo, video);
        this.videoRepository.save(video);
        Video result = new Video();
        Utils.copy(video, result);
        return result;
    }

    @Override
    public Page<Video> getAllVideo(GetAllVideo getAllVideo) {
        return this.videoRepository.findAll(new PageRequest(getAllVideo.getPage(), getAllVideo.getSize(), Sort.Direction.ASC, "lastModifiedTime"));
    }

    @Override
    public Page<Video> getAllVideoByEnable(GetAllVideoByEnable getAllVideoByEnable) {
        Assert.notNull(getAllVideoByEnable, "参数不能为空");
        return this.videoRepository.findByEnabledAndDeleted(getAllVideoByEnable.isEnable(), false,
                new PageRequest(getAllVideoByEnable.getPage(), getAllVideoByEnable.getSize()));
    }
}
